package com.yykj.base.server.service.impl;

import com.yykj.base.client.dto.template.ConsultationTemplateDTO;
import com.yykj.base.client.dto.template.ConsultationTemplateFieldDTO;
import com.yykj.base.client.dto.template.ConsultationTemplateFieldListDTO;
import com.yykj.base.server.converter.ConsultationTemplateDTOConverter;
import com.yykj.base.server.model.entity.form.template.CommonFormField;
import com.yykj.base.server.model.entity.form.template.ConsultationTemplate;
import com.yykj.base.server.model.entity.form.template.ConsultationTemplateField;
import com.yykj.base.server.model.repository.form.template.CommonFormFieldRepository;
import com.yykj.base.server.model.repository.form.template.ConsultationTemplateFieldRepository;
import com.yykj.base.server.model.repository.form.template.ConsultationTemplateRepository;
import com.yykj.base.server.service.ConsultationTemplateService;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ConsultationTemplateServiceImpl implements ConsultationTemplateService {
    @Override
    public ConsultationTemplateDTO editConsultationTemplate(ConsultationTemplateDTO consultationTemplateDTO) {
        ConsultationTemplate template;
        if (consultationTemplateDTO.getId() != null && consultationTemplateDTO.getId() > 0) {
            template = consultationTemplateRepository.findById(consultationTemplateDTO.getId()).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
        } else {
            template = new ConsultationTemplate();
        }
        LocalObjectUtil.copyNullValue(consultationTemplateDTO, template);
        template = consultationTemplateRepository.save(template);
        BeanUtils.copyProperties(template, consultationTemplateDTO);
        return consultationTemplateDTO;
    }

    @Override
    public void editConsultationTemplateFields(ConsultationTemplateFieldListDTO listDTO) {
        List<ConsultationTemplateField> list = new ArrayList<>();

        //1 检查需要添加字段名称是否与通用的一样
        List<String> fieldNames = new ArrayList<>();
        Map<String, Integer> nameMap = new HashMap<>();
        for (ConsultationTemplateFieldDTO templateFieldDTO : listDTO.getFieldList()) {

            templateFieldDTO.setName(StringUtils.trimAllWhitespace(templateFieldDTO.getName()));
            fieldNames.add(templateFieldDTO.getName());

            Integer orDefault = nameMap.getOrDefault(templateFieldDTO.getName(), 0);
            if (orDefault >= 1) {
                throw new NormalException(ResultEnums.PARAM_ERROR, templateFieldDTO.getName() + " 存在多个");
            }
            nameMap.put(templateFieldDTO.getName(), orDefault + 1);
        }

        List<CommonFormField> commonFormFieldList = commonFormFieldRepository.findAllByNameIn(fieldNames);
        if (commonFormFieldList != null && commonFormFieldList.size() > 0) {
            throw new NormalException(ResultEnums.COMMON_FIELD_EXIST_ERROR);
        }

        //找出字段里面有没有同样的
        List<ConsultationTemplateField> fieldList = templateFieldRepository.findAllByTemplateId(listDTO.getTemplateId());
        Map<String, ConsultationTemplateField> nameFieldMap = new HashMap<>();
        Map<Integer, ConsultationTemplateField> idFieldMap = new HashMap<>();
        for (ConsultationTemplateField field : fieldList) {
            nameFieldMap.put(field.getName(), field);
            idFieldMap.put(field.getId(), field);
        }
        ConsultationTemplateField keyField;
        ConsultationTemplateField keyField2;
        for (ConsultationTemplateFieldDTO templateFieldDTO : listDTO.getFieldList()) {
            ConsultationTemplateField currentTemplateField = new ConsultationTemplateField();
            //检查新增的与现有的名称是否重复
            keyField = nameFieldMap.get(templateFieldDTO.getName());
            if (keyField == null) {//没有重复的,直接加到里面
                BeanUtils.copyProperties(templateFieldDTO, currentTemplateField);
                currentTemplateField.setTemplateId(listDTO.getTemplateId());
                list.add(currentTemplateField);
            } else {//找到相同的名称
                if (templateFieldDTO.getId() == null || templateFieldDTO.getId() <= 0) {//新增
                    throw new NormalException(ResultEnums.ALL_READY_EXIST, keyField.getName() + " 已经存在");
                } else {//修改
                    //检查修改的与现有的名称是否重复
                    keyField2 = idFieldMap.get(templateFieldDTO.getId());
                    if(keyField.getId().equals(keyField2.getId())){//修改本条
                        LocalObjectUtil.copyNullValue(templateFieldDTO,keyField2);
                        list.add(keyField2);
                    }else{//修改的名称与现有的相同了。
                        throw new NormalException(ResultEnums.ALL_READY_EXIST, keyField.getName() + " 已经存在");
                    }

                }


            }
        }
        templateFieldRepository.saveAll(list);
    }

    @Override
    public void deleteConsultationTemplate(Integer id) {
        List<ConsultationTemplateField> allByTemplateId = templateFieldRepository.findAllByTemplateId(id);
        templateFieldRepository.deleteAll(allByTemplateId);
        consultationTemplateRepository.deleteById(id);
    }

    @Override
    public void deleteConsultationTemplateFields(Integer id) {
        templateFieldRepository.deleteById(id);
    }

    @Override
    public List<ConsultationTemplateDTO> listConsultationTemplate() {
        List<ConsultationTemplate> all = consultationTemplateRepository.findAll();
        return ConsultationTemplateDTOConverter.convert(all);
    }

    @Override
    public List<ConsultationTemplateFieldDTO> listConsultationTemplateFields(Integer id) {
        List<ConsultationTemplateField> templateFieldList = templateFieldRepository.findAllByTemplateId(id);
        ConsultationTemplateFieldDTO dto;
        List<ConsultationTemplateFieldDTO> list = new ArrayList<>();
        for (ConsultationTemplateField templateField : templateFieldList) {
            dto = new ConsultationTemplateFieldDTO();
            BeanUtils.copyProperties(templateField, dto);
            list.add(dto);
        }
        return list;
    }


    private ConsultationTemplateRepository consultationTemplateRepository;

    private ConsultationTemplateFieldRepository templateFieldRepository;

    private CommonFormFieldRepository commonFormFieldRepository;

    @Autowired
    public void setConsultationTemplateRepository(ConsultationTemplateRepository consultationTemplateRepository) {
        this.consultationTemplateRepository = consultationTemplateRepository;
    }

    @Autowired
    public void setTemplateFieldRepository(ConsultationTemplateFieldRepository templateFieldRepository) {
        this.templateFieldRepository = templateFieldRepository;
    }

    @Autowired
    public void setCommonFormFieldRepository(CommonFormFieldRepository commonFormFieldRepository) {
        this.commonFormFieldRepository = commonFormFieldRepository;
    }
}
